{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "bb6538d8-2a5d-4a99-b2c1-7130963e4f7b",
   "metadata": {},
   "source": [
    "# Microsoft Autogen Chat Example\n",
    "\n",
    "AgentOps automatically configures itself when it's initialized meaning your agent run data will be tracked and logged to your AgentOps dashboard right away."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87626697",
   "metadata": {},
   "source": [
    "First let's install the required packages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9599cf93",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install -U autogen-agentchat\n",
    "%pip install -U \"autogen-ext[openai]\"\n",
    "%pip install -U agentops\n",
    "%pip install -U python-dotenv"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3506f401",
   "metadata": {},
   "source": [
    "Then import them"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1b5c8b7b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from dotenv import load_dotenv\n",
    "from IPython.core.error import (\n",
    "    StdinNotImplementedError,\n",
    ")\n",
    "import asyncio\n",
    "\n",
    "import agentops\n",
    "\n",
    "from autogen_agentchat.agents import AssistantAgent, UserProxyAgent\n",
    "from autogen_ext.models.openai import OpenAIChatCompletionClient\n",
    "\n",
    "from autogen_agentchat.teams import RoundRobinGroupChat\n",
    "from autogen_agentchat.conditions import MaxMessageTermination\n",
    "from autogen_agentchat.ui import Console"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70b502a2",
   "metadata": {},
   "source": [
    "Next, we'll set our API keys. There are several ways to do this, the code below is just the most foolproof way for the purposes of this notebook. It accounts for both users who use environment variables and those who just want to set the API Key here in this notebook.\n",
    "\n",
    "[Get an AgentOps API key](https://agentops.ai/settings/projects)\n",
    "\n",
    "1. Create an environment variable in a .env file or other method. By default, the AgentOps `init()` function will look for an environment variable named `AGENTOPS_API_KEY`. Or...\n",
    "\n",
    "2. Replace `<your_agentops_key>` below and pass in the optional `api_key` parameter to the AgentOps `init(api_key=...)` function. Remember not to commit your API key to a public repo!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7ae4152d",
   "metadata": {},
   "outputs": [],
   "source": [
    "load_dotenv()\n",
    "os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
    "os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d93f2339-7b99-4cf1-9232-c24faba49c7b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# When initializing AgentOps, you can pass in optional tags to help filter sessions\n",
    "agentops.init(auto_start_session=False)\n",
    "tracer = agentops.start_trace(\n",
    "    trace_name=\"Microsoft Agent Chat Example\", tags=[\"autogen-chat\", \"microsoft-autogen\", \"agentops-example\"]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7858f0f6-9aca-4cdb-a514-9fbf7e353d50",
   "metadata": {},
   "source": [
    "AutoGen will now start automatically tracking\n",
    "\n",
    "* LLM prompts and completions\n",
    "* Token usage and costs\n",
    "* Agent names and actions\n",
    "* Correspondence between agents\n",
    "* Tool usage\n",
    "* Errors"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e875dd0c",
   "metadata": {},
   "source": [
    "# Simple Chat Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2962d990-f7ef-43d8-ba09-d29bd8356d9f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define model and API key\n",
    "model_name = \"gpt-4-turbo\"  # Or \"gpt-4o\" / \"gpt-4o-mini\" as per migration guide examples\n",
    "api_key = os.getenv(\"OPENAI_API_KEY\")\n",
    "\n",
    "# Create the model client\n",
    "model_client = OpenAIChatCompletionClient(model=model_name, api_key=api_key)\n",
    "\n",
    "# Create the agent that uses the LLM.\n",
    "assistant = AssistantAgent(\n",
    "    name=\"assistant\",\n",
    "    system_message=\"You are a helpful assistant.\",  # Added system message for clarity\n",
    "    model_client=model_client,\n",
    ")\n",
    "\n",
    "user_proxy_initiator = UserProxyAgent(\"user_initiator\")\n",
    "\n",
    "\n",
    "async def main():\n",
    "    termination = MaxMessageTermination(max_messages=2)\n",
    "\n",
    "    group_chat = RoundRobinGroupChat(\n",
    "        [user_proxy_initiator, assistant],  # Corrected: agents as positional argument\n",
    "        termination_condition=termination,\n",
    "    )\n",
    "\n",
    "    chat_task = \"How can I help you today?\"\n",
    "    print(f\"User Initiator: {chat_task}\")\n",
    "\n",
    "    try:\n",
    "        stream = group_chat.run_stream(task=chat_task)\n",
    "        await Console().run(stream)\n",
    "        agentops.end_trace(tracer, end_state=\"Success\")\n",
    "\n",
    "    except StdinNotImplementedError:\n",
    "        print(\"StdinNotImplementedError: This typically happens in non-interactive environments.\")\n",
    "        print(\"Skipping interactive part of chat for automation.\")\n",
    "        agentops.end_trace(tracer, end_state=\"Indeterminate\")\n",
    "    except Exception as e:\n",
    "        print(f\"An error occurred: {e}\")\n",
    "        agentops.end_trace(tracer, end_state=\"Error\")\n",
    "    finally:\n",
    "        await model_client.close()\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    try:\n",
    "        loop = asyncio.get_running_loop()\n",
    "    except RuntimeError:\n",
    "        loop = None\n",
    "\n",
    "    if loop and loop.is_running():\n",
    "        import nest_asyncio\n",
    "\n",
    "        nest_asyncio.apply()\n",
    "        asyncio.run(main())\n",
    "    else:\n",
    "        asyncio.run(main())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b422137-903a-41ef-a4ca-95b50aea4138",
   "metadata": {},
   "source": [
    "You can view data on this run at [app.agentops.ai](https://app.agentops.ai).\n",
    "\n",
    "The dashboard will display LLM events for each message sent by each agent, including those made by the human user."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "agentops (3.11.11)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
